<template>
  <div class="searchSuggestion">
    <van-cell @click="onSearch(item)" v-for="item in suggestion" :key="item" icon="search" >
      <template #title>
        <div v-html="highText(item)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  name: 'SearchSuggestion',
  data () {
    return {
      suggestion: []
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  beforeDestroy () {
    // 组件销毁时，清除延时器
    clearTimeout(this.setId)
  },
  // 监听
  watch: {
    searchText: {
      immediate: true,
      handler (newVal) {
        // 延时防抖
        // 清除上一个延时器
        if (this.setId) {
          clearTimeout(this.setId)
        }
        this.setId = setTimeout(async () => {
          // 获取联想建议
          const res = await getSearchSuggestion(newVal)
          // 保存数据
          this.suggestion = res.options
        })
      }
    }
  },
  created () {

  },

  methods: {
    // 处理数据
    highText (item) {
      const replaceStr = '<span style="color:red">' + this.searchText + '</span>'
      // 正则
      const reg = new RegExp(this.searchText, 'gi')
      // console.dir(reg)
      return item.replace(reg, replaceStr)
    },
    // 给父组件传值，改变搜索框的值
    onSearch (item) {
      this.$emit('onSearch', item)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
